package design_patterns;

/**
 * @author zhoude
 * @date 2022/6/29
 * 单例模式，类只生成一个实例
 */
public class Singleton {

    /**
     * 持有私有静态实例，防止被引用，此处赋值为null，目的是实现延迟加载
     */
    private static Singleton instance = null;

    /**
     * 私有构造方法，防止被实例化
     */
    private Singleton() { }

    /**
     * 防止序列化破坏单例模式
     */
    public Object readResolve() {
        return instance;
    }

    /**
     * 创建实例
     */
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    /**
     * 线程安全创建实例2
     */
    public static synchronized Singleton getInstance2() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    /**
     * 线程安全创建实例3
     */
    public static Singleton getInstance3() {
        if (instance == null) {
            synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    /**
     * 线程安全创建实例4
     */
    private static Singleton getInstance4() {
        return SingletonFactory.instance;
    }
    /**
     * 使用内部类来维护单例
     */
    private static class SingletonFactory {
        private static Singleton instance = new Singleton();
    }



}
